
public class TwoStacks {
	
	private Object[] stackStorage;
	private int firstStack;
	private int secondStack;

	class StackColissionException extends Exception {
		//private static final long serialVersionUID = 1337133713371337l;
		StackColissionException(){}
		StackColissionException(String msg){
		super (msg);
		}
	}
	class ForwardIterator implements java.util.Iterator<Object>  {
		private Object current = null; // merkt sich das aktuelle Element ...
		private int c;
		
		ForwardIterator(){
			c=0;
		}
		public boolean hasNext() {
			return c<firstStack;
		}
		public Object next() {
			if(hasNext()){
				current = stackStorage[c];
				c++;
				return current;
			}
			throw new java.util.NoSuchElementException(); 
		}
		public void remove() {
			throw new UnsupportedOperationException() ;
		}
	}
	
	class BackwardIterator implements java.util.Iterator<Object>  {
		private Object current = null; // merkt sich das aktuelle Element ...
		private int c;
		BackwardIterator (){
			c=secondStack+1;
		}
		public boolean hasNext() {
			return c<stackStorage.length;
		}
		public Object next() {
			if (hasNext()){
				current = stackStorage[c];
				c++;
				return current;
			}
			throw new java.util.NoSuchElementException(); 
		}
		public void remove() {
			throw new UnsupportedOperationException() ;
		}
	}
	
	TwoStacks(int i){
		stackStorage = new Object[i];
		firstStack = 0;
		secondStack = i-1;
	}
	public int getFirstStack(){
		return firstStack;
	}
	public int getSecondStack(){
		return secondStack;
	}
	public int getLength(){
		return stackStorage.length;
	}
	
	public void pushOne(Object e) throws StackColissionException{
//		if (stackStorage[firstStack] != null)
//			throw new Exception("Belegt 1");
		stackStorage[firstStack] = e;
		firstStack++;
		if (check())
			throw new StackColissionException("FIRST Stack Touched SECOND Stack"); 
	}
	public void pushTwo(Object e) throws StackColissionException{
// 		if (stackStorage[secondStack] != null)
//			throw new Exception("Belegt 2");
		stackStorage[secondStack] = e;
		secondStack--;
		if (check())
			throw new StackColissionException("SECOND Stack Touched FIRST Stack"); 
	}
	
	public Object popOne() {
		Object help;
		if (firstStack > 0){
			firstStack--;
			help = stackStorage[firstStack];
			stackStorage[firstStack] = null;
			return help;
		}
		return null;
	}
	
	public Object popTwo() {
		Object help;
		if (secondStack < stackStorage.length-1){
			secondStack++;
			help = stackStorage[secondStack];
			stackStorage[secondStack] = null;
			return help;
		}
		return null;
	}
	private boolean check(){
		return (firstStack > secondStack+1);
	}

	public ForwardIterator ForwardIterator(){
		return new ForwardIterator();
	}
	public BackwardIterator BackwardIterator(){
		return new BackwardIterator();
	}
	
}
